<!-- 工艺管理 -->
<template>
  <div class="technology-management">
    <div class="title-section">
      <h2>工艺管理</h2>
      <button class="btn-primary" @click="showAddDialog">新建</button>
    </div>

    <!-- 筛选区域 -->
    <div class="controls-section">
      <div class="filters">
        <div class="filter-item">
          <label>工艺编号</label>
          <input type="text" v-model="searchForm.processCode" placeholder="请输入工艺编号">
        </div>
        <div class="filter-item">
          <label>工艺名称</label>
          <input type="text" v-model="searchForm.processName" placeholder="请输入工艺名称">
        </div>
        <div class="filter-item">
          <label>产品编号</label>
          <input type="text" v-model="searchForm.productCode" placeholder="请输入产品编号">
        </div>
        <div class="filter-item">
          <label>产品名称</label>
          <input type="text" v-model="searchForm.productName" placeholder="请输入产品名称">
        </div>
        <div class="filter-item">
          <label>状态</label>
          <select v-model="searchForm.status">
            <option value="">全部</option>
            <option value="0">启用</option>
            <option value="1">停用</option>
          </select>
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="searchProcess">搜索</button>
        <button class="btn-secondary" @click="resetSearch">重置</button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll"></th>
            <th>工艺名称</th>
            <th>适用产品</th>
            <th>规格</th>
            <th>分类</th>
            <th>单位</th>
            <th>创建人</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in tableData" :key="row.id || index">
            <td><input type="checkbox" v-model="row.selected" @change="updateSelectAll"></td>
            <td class="link-style" @click="viewProcess(row)">
              {{ row.processName }}
              <div class="sub">{{ row.processCode }}</div>
            </td>
            <td class="link-style">
              {{ row.productName }}
              <div class="sub">{{ row.productCode }}</div>
            </td>
            <td>{{ row.specification }}</td>
            <td>{{ getCategoryName(row.category) }}</td>
            <td>{{ row.unitName }}</td>
            <td>{{ row.username }}</td>
            <td>
              <span :class="['status-badge', row.status === 0 ? 'status-active' : 'status-inactive']">
                {{ row.status === 0 ? '启用' : '停用' }}
              </span>
            </td>
            <td>
              <button class="btn-link" @click="editProcess(row)">编辑</button>
              <button class="btn-link btn-danger" @click="deleteProcess(row)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
        <label>全选</label>
        <button class="btn-secondary" @click="exportSelected">导出</button>
      </div>
      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage <= 1">&lt;</button>
        <button v-for="page in visiblePages" :key="page" :class="{ active: currentPage === page }" @click="goToPage(page)">{{ page }}</button>
        <button @click="nextPage" :disabled="currentPage >= totalPages">&gt;</button>
        <select v-model="pageSize" @change="onPageSizeChange">
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
      </div>
    </div>

    <!-- 添加/编辑工艺弹窗 -->
    <div v-if="showDialog" class="dialog-overlay" @click="closeDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>{{ isEdit ? '编辑工艺' : '新建工艺' }}</h3>
          <button class="btn-close" @click="closeDialog">&times;</button>
        </div>
        <div class="dialog-body">
          <form @submit.prevent="submitForm">
            <div class="form-group">
              <label>工艺名称 <span class="required">*</span></label>
              <input type="text" v-model="formData.processName" placeholder="请输入工艺名称" required>
            </div>
            <div class="form-group">
              <label>适用产品ID <span class="required">*</span></label>
              <input type="number" v-model="formData.productId" placeholder="请输入适用产品ID" required>
            </div>
            <div class="form-group">
              <label>规格</label>
              <input type="text" v-model="formData.specification" placeholder="请输入规格">
            </div>
            <div class="form-group">
              <label>分类</label>
              <select v-model="formData.category">
                <option value="">请选择分类</option>
                <option value="0">成品</option>
                <option value="1">半成品</option>
                <option value="2">残次品</option>
              </select>
            </div>
            <div class="form-group">
              <label>单位ID <span class="required">*</span></label>
              <input type="number" v-model="formData.unitId" placeholder="请输入单位ID" required>
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model="formData.status">
                <option value="0">启用</option>
                <option value="1">停用</option>
              </select>
            </div>
            <div class="form-group">
              <label>备注</label>
              <textarea v-model="formData.remark" placeholder="请输入备注"></textarea>
            </div>
            <div class="form-actions">
              <button type="button" class="btn-secondary" @click="closeDialog">取消</button>
              <button type="submit" class="btn-primary">{{ isEdit ? '保存' : '创建' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 工艺详情弹窗 -->
    <div v-if="showDetailDialog" class="dialog-overlay" @click="closeDetailDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>工艺详情</h3>
          <button class="btn-close" @click="closeDetailDialog">&times;</button>
        </div>
        <div class="dialog-body">
          <div class="detail-item">
            <label>工艺编号：</label>
            <span>{{ currentProcess.processCode }}</span>
          </div>
          <div class="detail-item">
            <label>工艺名称：</label>
            <span>{{ currentProcess.processName }}</span>
          </div>
          <div class="detail-item">
            <label>适用产品：</label>
            <span>{{ currentProcess.productName }}</span>
          </div>
          <div class="detail-item">
            <label>规格：</label>
            <span>{{ currentProcess.specification || '无' }}</span>
          </div>
          <div class="detail-item">
            <label>分类：</label>
            <span>{{ getCategoryName(currentProcess.category) || '无' }}</span>
          </div>
          <div class="detail-item">
            <label>单位：</label>
            <span>{{ currentProcess.unitName }}</span>
          </div>
          <div class="detail-item">
            <label>状态：</label>
            <span :class="['status-badge', currentProcess.status === 0 ? 'status-active' : 'status-inactive']">
              {{ currentProcess.status === 0 ? '启用' : '停用' }}
            </span>
          </div>
          <div class="detail-item">
            <label>创建人：</label>
            <span>{{ currentProcess.username || '无' }}</span>
          </div>
          <div class="detail-item">
            <label>备注：</label>
            <span>{{ currentProcess.remark || '无' }}</span>
          </div>
          <div class="form-actions">
            <button class="btn-secondary" @click="closeDetailDialog">关闭</button>
            <button class="btn-primary" @click="editProcess(currentProcess)">编辑</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { processManagementApi } from '@/api/processManagement'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'TechnologyManagement',
  data() {
    return {
      selectAll: false,
      currentPage: 1,
      pageSize: 10,
      totalPages: 0,
      total: 0,
      tableData: [],
      loading: false,

      // 搜索表单
      searchForm: {
        processCode: '',
        processName: '',
        productCode: '',
        productName: '',
        status: ''
      },

      // 弹窗控制
      showDialog: false,
      showDetailDialog: false,
      isEdit: false,

      // 表单数据
      formData: {
        id: null,
        processName: '',
        productId: null,
        specification: '',
        category: '',
        unitId: null,
        status: 0,
        remark: ''
      },

      // 当前选中的工艺
      currentProcess: {}
    }
  },

  computed: {
    visiblePages() {
      const pages = []
      const start = Math.max(1, this.currentPage - 2)
      const end = Math.min(this.totalPages, this.currentPage + 2)

      for (let i = start; i <= end; i++) {
        pages.push(i)
      }
      return pages
    }
  },

  mounted() {
    this.loadProcessData()
  },

  methods: {
    // 加载工艺数据
    async loadProcessData() {
      this.loading = true
      try {
        const params = {
          current: this.currentPage,
          size: this.pageSize,
          ...this.searchForm
        }

        const response = await processManagementApi.getProcessManagementPage(params)
        if (response.data && response.data.data) {
          const result = response.data.data
          const records = Array.isArray(result.records) ? result.records : []
          this.tableData = records.map((item) => ({
            selected: false,
            id: item.id,
            processCode: item.processCode,
            processName: item.processName,
            productId: item.productId,
            productCode: item.productCode,
            productName: item.productName,
            specification: item.specification,
            category: item.category,
            unitId: item.unitId,
            unitName: item.unitName,
            status: typeof item.status === 'number' ? item.status : (item.status === '启用' ? 0 : 1),
            username: item.username,
            remark: item.remark || ''
          }))
          this.total = Number(result.total) || this.tableData.length
          this.totalPages = Math.ceil(this.total / Number(this.pageSize || 10))
        }
      } catch (error) {
        console.error('加载工艺数据失败:', error)
        ElMessage.error('加载工艺数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索工艺
    searchProcess() {
      this.currentPage = 1
      this.loadProcessData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        processCode: '',
        processName: '',
        productCode: '',
        productName: '',
        status: ''
      }
      this.currentPage = 1
      this.loadProcessData()
    },

    // 显示添加弹窗
    showAddDialog() {
      this.isEdit = false
      this.formData = {
        id: null,
        processName: '',
        productId: null,
        specification: '',
        category: '',
        unitId: null,
        status: 0,
        remark: ''
      }
      this.showDialog = true
    },

    // 显示编辑弹窗
    async editProcess(row) {
      this.isEdit = true
      try {
        // 先获取详细信息
        const response = await processManagementApi.getProcessManagementById(row.id)
        const process = response.data?.data || row

        this.formData = {
          id: process.id,
          processName: process.processName,
          productId: process.productId,
          specification: process.specification || '',
          category: process.category || '',
          unitId: process.unitId,
          status: process.status,
          remark: process.remark || ''
        }
        this.showDialog = true
      } catch (error) {
        // 如果获取详情失败，使用行数据
        this.formData = {
          id: row.id,
          processName: row.processName,
          productId: row.productId,
          specification: row.specification || '',
          category: row.category || '',
          unitId: row.unitId,
          status: row.status,
          remark: row.remark || ''
        }
        this.showDialog = true
      }
    },

    // 查看工艺详情
    viewProcess(row) {
      this.currentProcess = { ...row }
      this.showDetailDialog = true
    },

    // 删除工艺
    async deleteProcess(row) {
      try {
        await ElMessageBox.confirm(
          `确定要删除工艺"${row.processName}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await processManagementApi.deleteProcessManagementById(row.id)
        if (response.data && response.data.code === 200) {
          ElMessage.success('删除成功')
          this.loadProcessData()
        } else {
          ElMessage.error(response.data?.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除工艺失败:', error)
          ElMessage.error('删除工艺失败')
        }
      }
    },

    // 提交表单
    async submitForm() {
      try {
        // 构建请求数据
        const payload = {
          processName: this.formData.processName,
          productId: Number(this.formData.productId),
          specification: this.formData.specification || '',
          category: this.formData.category || '',
          unitId: Number(this.formData.unitId),
          status: Number(this.formData.status),
          remark: this.formData.remark || ''
        }

        // 编辑时需要ID
        if (this.isEdit) {
          payload.id = this.formData.id
        }

        let response
        if (this.isEdit) {
          response = await processManagementApi.updateProcessManagement(payload)
        } else {
          response = await processManagementApi.addProcessManagement(payload)
        }

        if (response.data && response.data.code === 200) {
          ElMessage.success(this.isEdit ? '修改成功' : '添加成功')
          this.closeDialog()
          this.loadProcessData()
        } else {
          ElMessage.error(response.data?.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    },

    // 关闭弹窗
    closeDialog() {
      this.showDialog = false
      this.formData = {
        id: null,
        processName: '',
        productId: null,
        specification: '',
        category: '',
        unitId: null,
        status: 0,
        remark: ''
      }
    },

    // 关闭详情弹窗
    closeDetailDialog() {
      this.showDetailDialog = false
      this.currentProcess = {}
    },

    // 分页相关方法
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.loadProcessData()
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.loadProcessData()
      }
    },

    goToPage(page) {
      this.currentPage = page
      this.loadProcessData()
    },

    onPageSizeChange() {
      this.currentPage = 1
      this.loadProcessData()
    },

    // 全选相关方法
    toggleSelectAll() {
      this.tableData.forEach(row => {
        row.selected = this.selectAll
      })
    },

    updateSelectAll() {
      this.selectAll = this.tableData.every(row => row.selected)
    },

    // 导出选中项
    exportSelected() {
      const selectedItems = this.tableData.filter(row => row.selected)
      if (selectedItems.length === 0) {
        ElMessage.warning('请先选择要导出的工艺')
        return
      }
      // TODO: 实现导出功能
      ElMessage.info(`已选择 ${selectedItems.length} 项工艺进行导出`)
    },

    // 获取分类名称
    getCategoryName(category) {
      const categoryMap = {
        '0': '成品',
        '1': '半成品',
        '2': '残次品'
      }
      return categoryMap[category] || category || '无'
    }
  }
}
</script>

<style scoped>
.technology-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.title-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section h2 {
  font-size: 20px;
  font-weight: bold;
  margin: 0;
}

.controls-section {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.filters {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  white-space: nowrap;
  font-weight: 500;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 150px;
  font-size: 14px;
}

.actions {
  display: flex;
  gap: 10px;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-primary:hover {
  background-color: #337ecc;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-secondary:hover {
  border-color: #409eff;
  color: #409eff;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #606266;
}

.link-style {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.link-style:hover {
  color: #337ecc;
}

.sub {
  color: #666;
  font-size: 12px;
  margin-top: 2px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background-color: #f0f9ff;
  color: #0ea5e9;
}

.status-inactive {
  background-color: #fef2f2;
  color: #ef4444;
}

.btn-link {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  padding: 4px 8px;
  margin: 0 4px;
  font-size: 14px;
}

.btn-link:hover {
  text-decoration: underline;
}

.btn-danger {
  color: #f56c6c;
}

.btn-danger:hover {
  color: #f78989;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.pagination button:hover:not(:disabled) {
  border-color: #409eff;
  color: #409eff;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #909399;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-close:hover {
  color: #606266;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #606266;
}

.required {
  color: #f56c6c;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #409eff;
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 详情样式 */
.detail-item {
  display: flex;
  margin-bottom: 16px;
  align-items: center;
}

.detail-item label {
  font-weight: 500;
  color: #606266;
  width: 100px;
  flex-shrink: 0;
}

.detail-item span {
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .controls-section {
    flex-direction: column;
    align-items: stretch;
  }

  .filters {
    justify-content: center;
  }

  .actions {
    justify-content: center;
  }

  .dialog-content {
    width: 95%;
    margin: 20px;
  }

  .footer-section {
    flex-direction: column;
    gap: 16px;
  }
}
</style>


